package com.sy.pet.service;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sy.pet.commom.enmu.AuditStatus;
import com.sy.pet.dto.PetAdoptionQueryDTO;
import com.sy.pet.dto.PetAdoptionRecordDTO;
import com.sy.pet.entity.PetAdoptionRecords;
import com.sy.pet.entity.PetInfo;
import com.sy.pet.mapper.PetAdoptionRecordsMapper;
import com.sy.pet.mapper.PetInfoMapper;
import com.sy.pet.vo.PetAdoptionRecordVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @Author: liangSY
 * @Date: 2024/9/16
 * @ClassName: PetAdoptionService
 * @Description: PetAdoptionService描述
 */
@Service
public class PetAdoptionService {
    @Value("${pet.file-request-url}")
    private String fileRequestUrl;
    @Autowired
    PetAdoptionRecordsMapper petAdoptionRecordsMapper;
    @Autowired
    PetInfoMapper petInfoMapper;

    /**
     * 添加宠物领域申请记录
     * @param dto
     */
    public void addPetAdoptionRecord(PetAdoptionRecordDTO dto) {
        String userId = StpUtil.getLoginIdAsString();
        PetAdoptionRecords build = PetAdoptionRecords.builder()
                .petId(dto.getPetId())
                .userId(userId)
                .receiverAddress(dto.getReceiverAddress())
                .receiverName(dto.getReceiverName())
                .receiverPhone(dto.getReceiverPhone())
                .remark(dto.getRemark())
                .status(AuditStatus.AUDIT.getCode())
                .createTime(LocalDateTime.now())
                .build();

        petAdoptionRecordsMapper.insert(build);
    }

    public IPage<PetAdoptionRecordVO> getPageData(PetAdoptionQueryDTO dto){
        Page<PetAdoptionRecordVO> page = new Page(dto.getPage(), dto.getSize());
        IPage<PetAdoptionRecordVO> pageData = petAdoptionRecordsMapper.getPageDto(page, dto);
        pageData.getRecords().stream().forEach(item -> {
            item.setCover(fileRequestUrl+item.getCover());
        });
        return pageData;
    }

    public void audit(String id,AuditStatus status) {
        PetAdoptionRecords petAdoptionRecords = petAdoptionRecordsMapper.selectById(id);
        petAdoptionRecords.setStatus(status.getCode());
        petAdoptionRecordsMapper.updateById(petAdoptionRecords);
        if(status == AuditStatus.PASS){
            PetInfo info = petInfoMapper.selectById(petAdoptionRecords.getPetId());
            info.setUpdateTime(LocalDateTime.now());
            info.setUserId(petAdoptionRecords.getUserId());
            petInfoMapper.updateById(info);
        }
    }
}
